package com.paimeng.controller;

import com.paimeng.bean.News_info;
import com.paimeng.bean.Page;
import com.paimeng.lucence.Searcher;
import com.paimeng.utils.SortByHotIndex;
import com.paimeng.utils.SortByTime;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * @author: 潘辉
 * @Title: Searcher
 * @ProjectName: paimeng
 * @Description: 对用户输入的关键词进行分析检索，得到相应查询结果
 * @date: 2021/6/8 21:40
 */
//@WebServlet("/Searcher")
public class SearcherServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final int perpagecount = 5;
    private static double singleSearchNum = 0;


    @Override
    @SuppressWarnings("unchecked")

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        long starTime = System.currentTimeMillis();
        request.setCharacterEncoding("UTF-8");
        //获取前端搜索框内容
        String queryStr = request.getParameter("queryStr");
        int curPageIndex = 1;

        String indexStr = request.getParameter("curPageIndex");
        if (request.getParameter("curPageIndex") != null) {
            curPageIndex = Integer.parseInt(indexStr);
        }
        //System.out.println("curIndex = " + curPageIndex);
        //获取索引所在的位置
        String indexPath = request.getServletContext().getRealPath("/index");
        //System.out.println(indexPath);
        List<News_info> results = null;
        //获取新闻排序方式
        String sortMethod = (String) request.getParameter("sortnews");
        results = Searcher.search(indexPath, queryStr, perpagecount, curPageIndex, sortMethod);
        if ("byTime".equals(sortMethod)) {
            results.sort(new SortByTime());
        }
        if ("byHotIndex".equals(sortMethod)) {
            results.sort(new SortByHotIndex());
        }

        //对展示结果进行分页
        Page pages = new Page(curPageIndex, results.size() / perpagecount + 1, perpagecount, results.size(),
                perpagecount * (curPageIndex - 1), perpagecount * curPageIndex, true, curPageIndex != 1);
        long endTime = System.currentTimeMillis();
        double totleTime = (double) (endTime - starTime) / 1000;

        //System.out.println(totleTime + "\t" + singleSearchNum);
        request.setAttribute("singleSearchNum", singleSearchNum);
        request.setAttribute("searchTime", totleTime);
        request.setAttribute("page", pages);
        request.setAttribute("queryStr", queryStr);
        request.setAttribute("results", results);
        request.getRequestDispatcher("reacherResult.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }


}
